package cn.anecansaitin.whimsy.common.attachment;

import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntTag;
import net.neoforged.neoforge.common.util.INBTSerializable;

public class HandCannonMagazine implements INBTSerializable<CompoundTag> {
    public int bulletCount;
    public int rechargeDelay;
    public int shootDelay;
    public int auxiliaryAttackDelay;

    /**
     * 进行cd的计算，并尝试装填弹药
     * @return 是否装填弹药
     */
    public int tick() {
        if (shootDelay > 0) {
            shootDelay--;
        }

        if (rechargeDelay > 0) {
            rechargeDelay--;
        }

        if (auxiliaryAttackDelay > 0) {
            auxiliaryAttackDelay--;
        }

        if (rechargeDelay <= 0 && bulletCount < 4) {
            bulletCount++;
            rechargeDelay = 8;
            return bulletCount;
        }

        return 0;
    }

    /**
     * 尝试进行射击
     * @return 本次射击所消耗的是哪一发弹药
     */
    public int shoot() {
        if (bulletCount > 0 && shootDelay <= 0 && auxiliaryAttackDelay <= 10) {
            shootDelay = 6;
            bulletCount--;
            rechargeDelay = 15;
            return bulletCount + 1;
        } else {
            return 0;
        }
    }

    /**
     * 尝试进行近战攻击
     * @return 是否成功近战
     */
    public boolean auxiliaryAttack() {
        if (auxiliaryAttackDelay <= 0) {
            auxiliaryAttackDelay = 20;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public CompoundTag serializeNBT() {
        CompoundTag tag = new CompoundTag();
        tag.putInt("bullet_count", bulletCount);
        tag.putInt("recharge_delay", rechargeDelay);
        return tag;
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        bulletCount = nbt.getInt("bullet_count");
        rechargeDelay = nbt.getInt("recharge_delay");
    }

    private int lastReload = 4;

    /**
     * @return 是否应当播放装弹音效。只在客户端调用
     */
    public boolean shouldPlayReloadSound() {
        if (rechargeDelay == 1 && lastReload != bulletCount) {
            lastReload = bulletCount;
            return true;
        } else {
            return false;
        }
    }
}
